#!/usr/bin/env python

import sys
import time
import heapq
import socket
import threading
import cPickle as cpickle

MAX_LENGTH = 2**15

class Heap:
    def __init__(self):
        self.queue = []
        self.lock = threading.Lock()
    def push(self, item):
        self.lock.acquire()
        heapq.heappush(self.list, item)
        self.lock.release()
    def pop(self):
        self.lock.acquire()
        item = heapq.heappop(self.list)
        self.lock.release()
        return item
    def foreach(self, func):
        self.lock.acquire()
        for item in self.list:
            item = func(item)
        self.lock.release()
    def size(self):
        self.lock.acquire()
        size = len(self.list)
        self.lock.release()
        return size

class Uac(threading.Thread, socket.socket):
    def __init__(self, requests, waiting):
        threading.Thread.__init__(self)
        socket.socket.__init__(self, socket.AF_INET, socket.SOCK_DGRAM)
        self.runnning = True
        self.requests = requests
        self.waiting = waiting
        self.start()
    def run(self):
        while self.runnning:
            if self.requests.size() > 0:
                request = self.requests.pop()
                self.sendto(request.data, request.address)
                self.waiting.push(request)
                time.sleep(0.1)

class Uas(threading.Thread):
    def __init__(self, address, requests, waiting):
        threading.Thread.__init__(self)
        socket.socket.__init__(self, socket.AF_INET, socket.SOCK_DGRAM)
        self.runnning = True
        self.address = address
        self.requests = requests
        self.waiting = waiting
        self.bind(address)
        self.start()
    def run(self):
        while self.running:
            request = self.recvfrom(MAX_LENGTH)
            if request.data.type

class Peer:
    def __init__(self, host, port):
        self.requests = Heap()
        self.waiting = Heap()
        self.uac = Uac()
